package com.situ.company.department.service;

import java.util.List;

import com.situ.company.department.dao.DepartmentDao;
import com.situ.company.department.model.DepartmentModel;
import com.situ.company.employee.dao.EmployeeDao;
import com.situ.company.employee.model.EmployeeModel;

public class DepartmentService {

	private DepartmentDao dao = new DepartmentDao();
	private EmployeeDao eDao = new EmployeeDao();

	/**
	 * 添加
	 * 现判断编号是否存在
	 * @param model
	 * @return
	 */
	public String insert(DepartmentModel model) {
		DepartmentModel mdb = selectModel(model);
		if (mdb != null) {
			return "E";
		}
		Integer result = dao.insert(model);
		return String.valueOf(result);// 将result变量result转换成字符串
	}

	/**
	 * 根据code删除，如果部门有员工则删除失败
	 * @param model
	 * @return
	 */
	public String delete(DepartmentModel model) {
		EmployeeModel m = new EmployeeModel();
		m.setCodeDept(model.getCode());
		int count = eDao.selectCount(m);
		if (count > 0) {
			return "E";
		}
		Integer result = dao.delete(model);
		return String.valueOf(result);
	}

	/**
	 * 修改
	 * @param model
	 * @return
	 */
	public String update(DepartmentModel model) {
		Integer result = dao.update(model);
		return String.valueOf(result);
	}

	/**
	 * 多条件模糊查询出一些记录
	 * @param model
	 * @return
	 */
	public List<DepartmentModel> selectList(DepartmentModel model) {// 多条件的模糊查询出一些记录
		String code = model.getCode();
		if (code != null)
			model.setCode("%" + code + "%");
		String name = model.getName();
		if (name != null)
			model.setName("%" + name + "%");
		return dao.selectList(model);
	}

	/**
	 * 根据主键code查询出唯一记录，不存在返回null
	 * 否则返回查询出的第一条记录
	 * @param model
	 * @return
	 */
	public DepartmentModel selectModel(DepartmentModel model) {
		DepartmentModel temp = new DepartmentModel();
		temp.setCode(model.getCode());
		List<DepartmentModel> list = dao.selectList(temp);
		// if(FmtEmpty.isEmpty(list))
		if (list == null || list.isEmpty())
			return null;
		return list.get(0);
	}

	/**
	 * 根据多条件的模糊查询出的记录条数
	 * 
	 * @param model
	 * @return int
	 */
	public int selectCount(DepartmentModel model) {
		DepartmentModel mdb = new DepartmentModel();
		String code = model.getCode();
		mdb.setCode(code == null ? "%%" : "%" + code + "%");
		String name = model.getName();
		mdb.setName(name == null ? "%%" : "%" + name + "%");
		return dao.selectCount(mdb);
	}

}
